import Vue from 'vue';
// 工具函数库

// 时间戳转日期
export const toDate = function (timeStamp) {
    // console.log('转为日期')
    const date = new Date(timeStamp);
    // console.log(date);
    const Y = date.getFullYear() + '.';
    const M = (date.getMonth() < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return Y + M + D;
};
// 时间戳转时间 formatTime(1545903266795, 'Y-M-D h:m:s')
export const toTime = function (stam, format) {
    let time = new Date(stam)
    let newArr = []
    let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
    newArr.push(time.getFullYear())
    newArr.push(formatNumber(time.getMonth() + 1))
    newArr.push(formatNumber(time.getDate()))

    newArr.push(formatNumber(time.getHours()))
    newArr.push(formatNumber(time.getMinutes()))
    newArr.push(formatNumber(time.getSeconds()))

    for (let i in newArr) {
        format = format.replace(formatArr[i], newArr[i])
    }
    return format;
}
const formatDate = function (stam, format="Y-M-D") {
    let time = new Date(stam)
    let newArr = []
    let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
    newArr.push(time.getFullYear())
    newArr.push(formatNumber(time.getMonth() + 1))
    newArr.push(formatNumber(time.getDate()))

    newArr.push(formatNumber(time.getHours()))
    newArr.push(formatNumber(time.getMinutes()))
    newArr.push(formatNumber(time.getSeconds()))

    for (let i in newArr) {
        format = format.replace(formatArr[i], newArr[i])
    }
    return format;
}
Vue.prototype.formatDate = formatDate

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n;
}
